<?php
require './classes/MapArea.php';
require './classes/KML.php';

$tmpCity = new MapArea;

function removeSpaces( $array){
	$toReturn = array();
	foreach( $array as $val){
		if($val != ""){
			$toReturn[] = trim($val);
		}		
	}
	return $toReturn;
}

// Read file
$county = $_GET["county"];
$filename = "./data/" . $county . ".dat";

if (file_exists($filename) && $f = fopen($filename, 'r'))
{
do {
    $line = fgets($f); // Read in line
	
	// Break into elements
	$tokens = explode(' ', $line); 
	$tokens = removeSpaces($tokens);
	
	if(count($tokens) == 2){ //Coord pair
		$tmpCity->addCoord( floatval($tokens[0]), floatval($tokens[1]));	
	}else if(count($tokens) == 3){ // First line id, coord pair
		$tmpCity = new MapArea;
		$tmpCity->setId($tokens[0]);
		$tmpCity->addCoord(floatval($tokens[1]), floatval($tokens[2]));
	}else if(count($tokens) == 1 && $tokens[0] == "-99999"){ // Outlier to city. Keep adding pts
		//echo $tmpCity->printCoords();
	}else if(count($tokens) == 1 && $tokens[0] == "END"){
		/* Sometimes this is not the end of the record. Islands and outliers are often included with the ID -99999 and listed after main entry
		echo "<br>End of city<br>";
		//echo $tmpCity->printCoords();
		echo "<br><br>";
		*/
	 
		header("Content-Type: application/vnd.google-earth.kml+xml;charset=ISO-8859-1");
		header("Vary: Accept");
		header("Content-Disposition: attachment; filename=\"$county.kml\"");
		
		ob_start("coordCallback");
		$tmpCity->printCoords();
		ob_end_flush(); flush();
		
		
	}
} while (!feof($f));
}else{
	echo "Invalid County!";
}

if($f != null){
	fclose($f);
}


function coordCallback($buffer){
	$newKML = new KML;
	return $newKML->getKML('Jon', $buffer);
}
?>